import config from '@/config'
import storage from '@/Util/storage'
import constant from '@/Util/constant.js'
import {
	getToken,
	setToken,
	removeToken
} from '@/Util/auth.js'
import SignApi from '@/Api/Sign.js'

const user = {
	state: {
		token: getToken(),
		userId: storage.get(constant.userId),
		userInfo: storage.get(constant.userInfo),
	},

	mutations: {
		SET_TOKEN: (state, token) => {
			state.token = token
		},

		SET_USERID: (state, userId) => {
			state.userId = userId
			storage.set(constant.userId, userId)
		},
		SET_USERINFO: (state, userInfo) => {
			state.userInfo = userInfo
			storage.set(constant.userInfo, userInfo)
		}
	},

	actions: {
		// 注册
		Sign({
			commit
		}, signData) {
			return new Promise((resolve, reject) => {
				SignApi.sign(signData).then(resp => {
					setToken(resp.data.token)
					commit('SET_TOKEN', resp.data.token)
					resolve()
				}).catch(error => {
					reject(error)
				})
			})
		},
		// 获取用户信息
		Login({
			commit,
			state
		}, code) {
			return new Promise((resolve, reject) => {
				SignApi.login(code).then(res => {
					const signed = res.data.signed
					if (signed) {
						const token = res.data.token
						const user = {
							...res.data.user,
							sexZh: res.data.user.sex === 1 ? '女' : '男'
						}
						setToken(token)
						commit('SET_TOKEN', token)
						commit('SET_USERID', user.userId)
						commit('SET_USERINFO', user)
					}
					resolve(signed)
				}).catch(error => {
					reject(error)
				})
			})
		},

		// 获取用户信息
		GetUserInfo({
			commit,
			state
		}) {
			return new Promise((resolve, reject) => {
				SignApi.userInfo().then(res => {
					const user = res.data
					if (user) {
						commit('SET_USERINFO', user)
						commit('SET_USERID', user.userId)
					}
					resolve(user)
				}).catch(error => {
					reject(error)
				})
			})
		},
	}
}

export default user